package main

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"github.com/xuri/excelize/v2"
)

func main() {
	// 检查当前目录是否为Git仓库
	if _, err := os.Stat(".git"); os.IsNotExist(err) {
		fmt.Println("当前目录不是Git仓库")
		return
	}

	// 获取当前分支名称
	branchCmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
	branchOutput, err := branchCmd.Output()
	if err != nil {
		fmt.Printf("获取分支名称失败: %v\n", err)
		return
	}
	branchName := strings.TrimSpace(string(branchOutput))

	// 获取最近50条提交日志（包含变更文件）
	logCmd := exec.Command("git", "log", "--pretty=format:%h;%an;%ad;%s", "--name-status", "-n", "50", branchName)
	logOutput, err := logCmd.Output()
	if err != nil {
		fmt.Printf("获取提交日志失败: %v\n", err)
		return
	}
	logs := strings.Split(string(logOutput), "\n")

	// 创建Excel文件
	f := excelize.NewFile()
	sheetName := "提交日志"
	f.SetSheetName("Sheet1", sheetName)

	// 设置表头
	headers := []string{"提交哈希", "作者", "提交日期", "提交信息", "变更文件"}
	for col, header := range headers {
		cell, _ := excelize.CoordinatesToCellName(col+1, 1)
		f.SetCellValue(sheetName, cell, header)
	}

	// 填充数据
	row := 2
	for i := 0; i < len(logs); i++ {
		if logs[i] == "" {
			continue
		}

		// 解析提交信息
		commitInfo := strings.Split(logs[i], ";")
		for col, field := range commitInfo {
			cell, _ := excelize.CoordinatesToCellName(col+1, row)
			f.SetCellValue(sheetName, cell, field)
		}

		// 解析变更文件
		var changedFiles []string
		for i+1 < len(logs) && logs[i+1] != "" && !strings.Contains(logs[i+1], ";") {
			changedFiles = append(changedFiles, logs[i+1])
			i++
		}

		// 写入变更文件
		cell, _ := excelize.CoordinatesToCellName(5, row)
		f.SetCellValue(sheetName, cell, strings.Join(changedFiles, "\n"))
		row++
	}

	// 保存Excel文件
	if err := f.SaveAs("git_logs.xlsx"); err != nil {
		fmt.Printf("保存Excel文件失败: %v\n", err)
		return
	}

	fmt.Println("提交日志和变更文件已成功导出到 git_logs.xlsx")
}